package realm.inorder.itmill.validator;

import com.itmill.toolkit.data.Validator;

public class EmailValidator implements Validator {

	private String exceptionMessage;
	
	public EmailValidator(String exceptionMessage) {
		super();
		this.exceptionMessage = exceptionMessage;
	}

	public boolean isValid(Object value) {
		String email = value.toString();
		
		String[] parts = email.split("@");
		
		if (parts.length == 2) {
			if (checkLocalName(parts[0]) && checkDomain(parts[1])) {
				return true;
			}
		}
		
		return false;
	}

	public void validate(Object value) throws InvalidValueException {
		if (!isValid(value)) {
			throw new InvalidValueException(exceptionMessage);
		}
    }
    
    protected boolean checkLocalName(String value) {
        String label = "[\\w|\\.|\\-]+";
        return value.matches(label);
    }
    
    protected boolean checkDomain(String value) {
        String label = "(\\p{Alpha}([\\p{Alnum}|-]*\\p{Alnum})*)(.(\\p{Alpha}([\\p{Alnum}|-]*\\p{Alnum})*))*";
        return value.matches(label);
    }

}
